document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('message-form');
    const nameInput = document.getElementById('name-input');
    const messageInput = document.getElementById('message-input');
    const messagesContainer = document.getElementById('messages-container');
    
    // 从本地存储加载留言
    loadMessages();
    
    // 表单提交事件
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const name = nameInput.value.trim();
        const message = messageInput.value.trim();
        
        if (name && message) {
            addMessage(name, message);
            nameInput.value = '';
            messageInput.value = '';
        }
    });
    
    // 添加留言函数
    function addMessage(name, text) {
        const messages = getStoredMessages();
        const newMessage = {
            id: Date.now(),
            name: name,
            text: text,
            timestamp: new Date().toLocaleString()
        };
        
        messages.unshift(newMessage);
        localStorage.setItem('messages', JSON.stringify(messages));
        renderMessages();
    }
    
    // 从本地存储获取留言
    function getStoredMessages() {
        return JSON.parse(localStorage.getItem('messages') || '[]');
    }
    
    // 加载并渲染留言
    function loadMessages() {
        renderMessages();
    }
    
    // 渲染留言列表
    function renderMessages() {
        const messages = getStoredMessages();
        messagesContainer.innerHTML = '';
        
        messages.forEach(msg => {
            const messageEl = document.createElement('div');
            messageEl.className = 'message';
            messageEl.innerHTML = `
                <strong>${msg.name}</strong>
                <span style="font-size: 12px; color: #999; margin-left: 10px;">${msg.timestamp}</span>
                <p>${msg.text}</p>
            `;
            messagesContainer.appendChild(messageEl);
        });
    }
});